# 导入必要的库
import argparse  # 用于解析命令行参数
import time  # 用于计时
from sys import platform  # 获取操作系统平台信息
from models import *  # 导入模型相关模块
from utils.datasets import *  # 导入数据集处理模块
from utils.utils import *  # 导入工具函数

from reid.data import make_data_loader  # 行人重识别数据加载器
from reid.data.transforms import build_transforms  # 行人重识别数据预处理
import sys  # 系统相关操作

from reid.modeling import build_model  # 构建行人重识别模型
from reid.config import cfg as reidCfg  # 行人重识别配置


def detect(cfg,
           data,
           weights,
           images='data/samples',  # 输入文件夹路径
           output='output',  # 输出文件夹路径
           fourcc='mp4v',  # 视频编码格式
           img_size=416,  # 图像大小
           conf_thres=0.5,  # 置信度阈值
           nms_thres=0.5,  # 非极大值抑制阈值
           dist_thres=1.0,  # 行人重识别距离阈值
           save_txt=False,  # 是否保存检测结果为文本文件
           save_images=True):  # 是否保存检测后的图像

    # 初始化
    device = torch_utils.select_device(force_cpu=False)  # 选择设备（优先GPU）
    torch.backends.cudnn.benchmark = False  # 关闭cuDNN的基准测试以获得可重复的结果
    if os.path.exists(output):
        shutil.rmtree(output)  # 如果输出文件夹存在则删除
    os.makedirs(output)  # 创建新的输出文件夹

    ############# 行人重识别模型初始化 #############
    query_loader, num_query = make_data_loader(reidCfg)  # 创建查询集数据加载器
    # reidModel = build_model(reidCfg, num_classes=10126)
    reidModel = build_model(reidCfg, num_classes=1501)  # 构建行人重识别模型
    reidModel.load_param(reidCfg.TEST.WEIGHT)  # 加载预训练权重
    reidModel.to(device).eval()  # 将模型移至设备并设置为评估模式

    query_feats = []  # 存储查询特征
    query_pids = []  # 存储查询ID

    for i, batch in enumerate(query_loader):
        with torch.no_grad():  # 禁用梯度计算
            img, pid, camid = batch  # 获取图像、行人ID和摄像头ID
            img = img.to(device)  # 将图像移至设备
            feat = reidModel(img)  # 提取特征，形状为[2, 2048]
            query_feats.append(feat)  # 添加特征到列表
            query_pids.extend(np.asarray(pid))  # 扩展行人ID列表

    query_feats = torch.cat(query_feats, dim=0)  # 拼接所有查询特征，形状为[2, 2048]
    print("The query feature is normalized")
    query_feats = torch.nn.functional.normalize(query_feats, dim=1, p=2)  # 对特征进行L2归一化

    ############# 行人检测模型初始化 #############
    model = Darknet(cfg, img_size)  # 构建Darknet行人检测模型

    # 加载权重
    if weights.endswith('.pt'):  # PyTorch格式的权重
        model.load_state_dict(torch.load(weights, map_location=device)['model'])
    else:  # Darknet格式的权重
        _ = load_darknet_weights(model, weights)

    # 评估模式
    model.to(device).eval()  # 将模型移至设备并设置为评估模式
    # 半精度
    opt.half = opt.half and device.type != 'cpu'  # 半精度仅在CUDA上支持
    if opt.half:
        model.half()  # 转换为半精度

    # 设置数据加载器
    vid_path, vid_writer = None, None  # 视频路径和视频写入器
    if opt.webcam:  # 使用网络摄像头
        save_images = False
        dataloader = LoadWebcam(img_size=img_size, half=opt.half)
    else:
        dataloader = LoadImages(images, img_size=img_size, half=opt.half)  # 加载图像

    # 获取类别和颜色
    # parse_data_cfg(data)['names']: 获取类别名称文件路径 names=data/coco.names
    classes = load_classes(parse_data_cfg(data)['names'])  # 加载类别名称列表: ['person', 'bicycle'...]
    colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(classes))]  # 为每个类别随机生成颜色

    # 运行推理
    t0 = time.time()
    for i, (path, img, im0, vid_cap) in enumerate(dataloader):
        t = time.time()
        # if i < 500 or i % 5 == 0:
        #     continue
        save_path = str(Path(output) / Path(path).name)  # 保存路径

        # 获取检测结果 shape: (3, 416, 320)
        img = torch.from_numpy(img).unsqueeze(0).to(device)  # torch.Size([1, 3, 416, 320])
        pred, _ = model(img)  # 模型预测
        det = non_max_suppression(pred.float(), conf_thres, nms_thres)[0]  # 非极大值抑制，torch.Size([5, 7])

        if det is not None and len(det) > 0:
            # 将边界框从416大小缩放到原始图像大小
            det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()

            # 打印结果到屏幕 image 1/3 data\samples\000493.jpg: 288x416 5 persons, Done. (0.869s)
            print('%gx%g ' % img.shape[2:], end='')  # 打印图像大小 '288x416'
            for c in det[:, -1].unique():  # 遍历所有检测到的类别
                n = (det[:, -1] == c).sum()  # 统计当前类别的数量
                if classes[int(c)] == 'person':
                    print('%g %ss' % (n, classes[int(c)]), end=', ')  # 打印数量和类别'5 persons'

            # 绘制边界框和标签
            # (x1y1x2y2, obj_conf, class_conf, class_pred)
            count = 0
            gallery_img = []
            gallery_loc = []  # 存储边界框坐标
            for *xyxy, conf, cls_conf, cls in det:  # 遍历所有检测框
                # *xyxy: 边界框的左上角和右下角坐标: [tensor(349.), tensor(26.), tensor(468.), tensor(341.)]
                if save_txt:  # 保存到文件
                    with open(save_path + '.txt', 'a') as file:
                        file.write(('%g ' * 6 + '\n') % (*xyxy, cls, conf))

                # 添加边界框到图像
                label = '%s %.2f' % (classes[int(cls)], conf)  # 'person 1.00'
                if classes[int(cls)] == 'person':
                    #plot_one_box(xyxy, im0, label=label, color=colors[int(cls)])
                    xmin = int(xyxy[0])
                    ymin = int(xyxy[1])
                    xmax = int(xyxy[2])
                    ymax = int(xyxy[3])
                    w = xmax - xmin  # 233
                    h = ymax - ymin  # 602
                    # 如果检测到的行人太小，则忽略
                    if w*h > 500:
                        gallery_loc.append((xmin, ymin, xmax, ymax))
                        crop_img = im0[ymin:ymax, xmin:xmax]  # 裁剪行人区域，HWC (602, 233, 3)

                        crop_img = Image.fromarray(cv2.cvtColor(crop_img, cv2.COLOR_BGR2RGB))  # 转换为PIL格式: (233, 602)
                        crop_img = build_transforms(reidCfg)(crop_img).unsqueeze(0)  # 预处理，torch.Size([1, 3, 256, 128])
                        gallery_img.append(crop_img)

            if gallery_img:
                gallery_img = torch.cat(gallery_img, dim=0)  # 拼接所有行人图像，torch.Size([7, 3, 256, 128])
                gallery_img = gallery_img.to(device)
                gallery_feats = reidModel(gallery_img)  # 提取特征，torch.Size([7, 2048])
                print("The gallery feature is normalized")
                gallery_feats = torch.nn.functional.normalize(gallery_feats, dim=1, p=2)  # 对特征进行L2归一化

                # m: 2 (查询特征数量)
                # n: 7 (图库特征数量)
                m, n = query_feats.shape[0], gallery_feats.shape[0]
                # 计算距离矩阵
                distmat = torch.pow(query_feats, 2).sum(dim=1, keepdim=True).expand(m, n) + \
                          torch.pow(gallery_feats, 2).sum(dim=1, keepdim=True).expand(n, m).t()
                # out=(beta∗M)+(alpha∗mat1@mat2)
                # qf^2 + gf^2 - 2 * qf@gf.t()
                # distmat - 2 * qf@gf.t()
                # distmat: qf^2 + gf^2
                # qf: torch.Size([2, 2048])
                # gf: torch.Size([7, 2048])
                distmat.addmm_(1, -2, query_feats, gallery_feats.t())
                # distmat = (qf - gf)^2
                # distmat = np.array([[1.79536, 2.00926, 0.52790, 1.98851, 2.15138, 1.75929, 1.99410],
                #                     [1.78843, 1.96036, 0.53674, 1.98929, 1.99490, 1.84878, 1.98575]])
                distmat = distmat.cpu().numpy()  # 转换为numpy数组，形状为(3, 12)
                distmat = distmat.sum(axis=0) / len(query_feats)  # 对查询中同一行人的多个结果取平均
                index = distmat.argmin()  # 找到最小距离的索引
                if distmat[index] < dist_thres:  # 如果最小距离小于阈值
                    print('距离：%s'%distmat[index])
                    plot_one_box(gallery_loc[index], im0, label='find!', color=colors[int(cls)])  # 绘制匹配的行人框
                    # cv2.imshow('person search', im0)
                    # cv2.waitKey()

        print('Done. (%.3fs)' % (time.time() - t))

        if opt.webcam:  # 显示实时摄像头画面
            cv2.imshow(weights, im0)

        if save_images:  # 保存检测后的图像
            if dataloader.mode == 'images':
                cv2.imwrite(save_path, im0)
            else:
                if vid_path != save_path:  # 新视频
                    vid_path = save_path
                    if isinstance(vid_writer, cv2.VideoWriter):
                        vid_writer.release()  # 释放之前的视频写入器

                    fps = vid_cap.get(cv2.CAP_PROP_FPS)  # 获取帧率
                    width = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))  # 获取宽度
                    height = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))  # 获取高度
                    vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*fourcc), fps, (width, height))
                vid_writer.write(im0)  # 写入帧

    if save_images:
        print('Results saved to %s' % os.getcwd() + os.sep + output)
        if platform == 'darwin':  # macOS
            os.system('open ' + output + ' ' + save_path)

    print('Done. (%.3fs)' % (time.time() - t0))


if __name__ == '__main__':
    parser = argparse.ArgumentParser()  # 创建参数解析器
    parser.add_argument('--cfg', type=str, default='cfg/yolov3.cfg', help="模型配置文件路径")
    parser.add_argument('--data', type=str, default='data/coco.data', help="数据集配置文件所在路径")
    parser.add_argument('--weights', type=str, default='weights/yolov3.weights', help='模型权重文件路径')
    parser.add_argument('--images', type=str, default='data/samples', help='需要进行检测的图片文件夹')
    parser.add_argument('-q', '--query', default=r'query', help='查询图片的读取路径.')
    parser.add_argument('--img-size', type=int, default=416, help='输入分辨率大小')
    parser.add_argument('--conf-thres', type=float, default=0.1, help='物体置信度阈值')
    parser.add_argument('--nms-thres', type=float, default=0.4, help='NMS阈值')
    parser.add_argument('--dist_thres', type=float, default=1.0, help='行人图片距离阈值，小于这个距离，就认为是该行人')
    parser.add_argument('--fourcc', type=str, default='mp4v', help='fourcc output video codec (verify ffmpeg support)')
    parser.add_argument('--output', type=str, default='output', help='检测后的图片或视频保存的路径')
    parser.add_argument('--half', default=False, help='是否采用半精度FP16进行推理')
    parser.add_argument('--webcam', default=False, help='是否使用摄像头进行检测')
    opt = parser.parse_args()  # 解析参数
    print(opt)

    with torch.no_grad():  # 禁用梯度计算
        detect(opt.cfg,
               opt.data,
               opt.weights,
               images=opt.images,
               img_size=opt.img_size,
               conf_thres=opt.conf_thres,
               nms_thres=opt.nms_thres,
               dist_thres=opt.dist_thres,
               fourcc=opt.fourcc,
               output=opt.output)